﻿using System;
using System.Collections;
using DG.Tweening;
using DG.Tweening.Core;
using DG.Tweening.Plugins.Options;
using Gp.Scripts.Equip;
using UnityEngine;
using UnityEngine.UI;

namespace Gp.Scripts.GUI {
    public class UnitArmorIcon : MonoBehaviour {
        public Image img;
        public Image coverImg;
        private ArmorFragmentEntity _info;


        private UnitLifeBarController _lifeBarController;
        public ArmorFragmentEntity Info => _info;

        [SerializeField] private Color brokenColor;
        [SerializeField] private Color normalColor;
        [SerializeField] private Color damageColor;

        [SerializeField] private float fadeTime = .2f;
        
        public void Init(ArmorFragmentEntity info, UnitLifeBarController controller) {
            _info = info;
            _lifeBarController = controller;

            info.OnDurabilityChanged += HandleDurabilityChanged;
            
            gameObject.SetActive(true);
        }


        private void HandleDurabilityChanged(object sender, EventArgs eventArgs) {
            // 如果已经损坏
            if (_info.IsBroken) {
                SetColor(damageColor);
                PlayBreak();
                return;
            }

            SetColor(Color.Lerp(brokenColor, normalColor, _info.CurDurabilityRate));
        }

        private Tween _tweenerCore;
        private void SetColor(Color color) {
            if (_tweenerCore.IsActive()) {
                _tweenerCore.Kill();
            }
            _tweenerCore = img.DOColor(color, fadeTime);
        }



        public void PlayBreak() {
            _lifeBarController.FreshPredictUI();
            StartCoroutine(BreakEffect());
        }





        private IEnumerator BreakEffect() {
            var cpy = Instantiate(coverImg, coverImg.transform.parent);
            cpy.color = Color.white;
            cpy.transform.DOScale(Vector3.one * 1.5f, .15f).SetEase(Ease.OutElastic);
            cpy.transform.DOLocalMoveY(15f, .1f).SetEase(Ease.OutElastic);
            cpy.DOFade(0, .3f);
            yield return new WaitForSeconds(.4f);
            Destroy(cpy);
        }
        
        
        

        private Tween _coverTween;
        private bool _isBlinking = false;
        public void Blink() {
            _coverTween?.Kill();
            _isBlinking = true;
            _coverTween = coverImg.DOFade(.5f, .2f);
        }

        public void UnBlink() {
            _coverTween?.Kill();
            _isBlinking = false;
            coverImg.DOFade(0f, 0f);
        }
    }
}